package com.js.data.dtmg.datasource;

import com.js.data.dtmg.dto.DtDatasourceDto;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class DataSourceConfig {


    public static DataSource getDataSource(DtDatasourceDto dto) {
        HikariConfig config = new HikariConfig();
        switch (dto.getDtType()){
            //mysql数据库
            case "1":
                setMysqlDataSource(config,dto);
                break;
            default:
              return null;
        }

        return new HikariDataSource(config);
    }
    private static void setMysqlDataSource(HikariConfig config,DtDatasourceDto dto){
        String url = "jdbc:mysql://{host}:{port}/{db}?allowPublicKeyRetrieval=true&useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8&tinyInt1isBit=false";
        url = url.replace("{host}", dto.getHost());
        url = url.replace("{port}", String.valueOf(dto.getPort()));
        url = url.replace("{db}", String.valueOf(dto.getDbName()));
        config.setJdbcUrl(url);
        config.setUsername(dto.getUserName());
        config.setPassword(dto.getPassword());
        config.addDataSourceProperty("cachePrepStmts", true); //是否自定义配置，为true时下面两个参数才生效
        config.setMaximumPoolSize(5);
        config.setMinimumIdle(300000);
        // 空闲超时 60s
        config.setIdleTimeout(60000);
        config.setMaxLifetime(3000);
        config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048); //单条语句最大长度默认256，官方推荐2048

        Properties properties = new Properties();
        //设置可以获取remarks信息
        properties.setProperty("remarks", "true");
        properties.setProperty("useInformationSchema", "true");
        config.setDataSourceProperties(properties);
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
    }
}
